/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.doclet;

import com.sun.javadoc.RootDoc;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 7/6/2017
 */
public abstract class DocGenerator implements FileVisitor<Path> {

    protected Logger logger = Logger.getLogger(getClass().getName());

    protected List<String> argumentList = new ArrayList<>();

    protected String sourcePath;

    protected String buildDir;

    public DocGenerator() {
        String hashcode = String.valueOf(this.hashCode());
        argumentList.add("-docGenerator");
        argumentList.add(hashcode);
        HermitDoclet.addToCache(hashcode, this);
    }

    public void generate() {
        argumentList.addAll(Arrays.asList(new String[]{
                "-sourcepath", sourcePath,
                "-doclet", HermitDoclet.class.getName()
        }));

        File rootDir = new File(sourcePath);
        try {
            Files.walkFileTree(rootDir.toPath(), this);
        } catch (IOException e) {
            logger.log(Level.SEVERE, e.getMessage(), e);
        }
        com.sun.tools.javadoc.Main.execute(argumentList.toArray(new String[]{}));
    }

    protected abstract void generate(RootDoc root);

    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        String filePath = file.toFile().getCanonicalPath();
        if (filePath.endsWith(".java")) {
            argumentList.add(filePath);
        } 
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        return FileVisitResult.CONTINUE;
    }

    public String getSourcePath() {
        return sourcePath;
    }

    public void setSourcePath(String sourcePath) {
        this.sourcePath = sourcePath;
    }

    public String getBuildDir() {
        return buildDir;
    }

    public void setBuildDir(String buildDir) {
        this.buildDir = buildDir;
    }
}
